/*
   @Copyright:LeetCode
   @Author:   tjyemail
   @Problem:  http://leetcode.com/problems/recover-binary-search-tree
   @Language: C++
   @Datetime: 19-07-11 11:03
   */

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
	TreeNode *pre=NULL, *p=NULL, *q=NULL;
	void inorder(TreeNode *root){
		if(root->left) inorder(root->left);
		if(pre && pre->val>root->val){
			if(p){
				swap(p->val, root->val);
				pre=p=q=NULL;
				return;
			}
			else{
				p=pre;
				q=root;
			}
		}
		pre=root;
		if(root->right) inorder(root->right);
	}
public:
	void recoverTree(TreeNode* root) {
		if(root==NULL) return;
		inorder(root);
		if(p) swap(p->val,q->val);
	}
};
